/**
 * electron主进程和子进程公用的工具类
 */
let JS_RANDOM_DATA = [];
let JS_RANDOM_DATA_FLAG = Date.now() + '';

export function getJsRandom(min, max) {
    // 每秒 100个
    if (JS_RANDOM_DATA_FLAG !== Date.now() + '') {
        JS_RANDOM_DATA = [];
        JS_RANDOM_DATA_FLAG = Date.now() + '';
    }
    if (!min) {
        min = 100;
    }
    if (!max) {
        max = 999;
    }
    let sjs = getRandomNum(min, max);
    let sjscc = JS_RANDOM_DATA_FLAG.substring(8, 5) + sjs;
    if (JS_RANDOM_DATA.indexOf(sjscc) < 0) {
        JS_RANDOM_DATA.push(sjscc);
        return sjscc;
    } else {
        return getJsRandom();
    }
}

export function getRandomNum(Min, Max) {
    let Range = Max - Min;
    let Rand = Math.random();
    return Min + Math.round(Rand * Range);
}

export function jsSleep(time, isZz) {
    isZz && window.pageLoading.openAll();
    return new Promise((resolve) => {
        setTimeout(() => {
            isZz && window.pageLoading.closeAll();
            resolve();
        }, time);
    });
}

/**
 *  函数防抖全局定义
 *  param fnName  函数名
 *  param time  延迟时间
 *  return: 处理后的执行函数
 */
export function debounceGol(fn, time) {
    let timeout = null;
    return function () {
        const _arguments = arguments;
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
            timeout = null;
            fn.apply(this, _arguments);
        }, time);
    };
}

// el-form组件封装
export async function formValidate(ref) {
    return new Promise((resolve, reject) => {
        ref.validate((valid) => {
            if (valid) {
                resolve(valid);
            } else {
                reject(new Error('验证失败'));
            }
        });
    });
}

export function getArrByIndex(arr, index) {
    if (arr && arr.length > index) {
        return arr[index];
    }
    return '';
}

// 如果报错就循环执行
export function setTimeOutExecAsync(fn, _that, opt = { timeOut: 1000, execFreq: 5 }) {
    return function () {
        const _arguments = arguments;
        return new Promise((resolve, reject) => {
            let settimeFun = (opt1) => {
                setTimeout(async () => {
                    try {
                        console.log(`第${opt1.execFreq}次执行`);
                        let ret = await fn.apply(_that, _arguments);
                        resolve(ret);
                    } catch (e) {
                        if (opt1.execFreq === 0) {
                            // throw new Error(e);
                            reject(e);
                        } else {
                            console.log('setTimeOutExec.error:', e, opt1.timeOut, opt1.execFreq);
                            let execFreqTmp = opt1.execFreq - 1;
                            settimeFun({ timeOut: opt1.timeOut, execFreq: execFreqTmp });
                        }
                    }
                }, opt1.timeOut);
            };
            settimeFun(opt);
        });
    };
}

// 立即执行函数 匿名函数 ，如果报错，就再次执行 execFreq 次
export function setTimeOutExecRetry(fn, opt = { timeOut: 1000, execFreq: 3 }) {
    return new Promise((resolve, reject) => {
        let settimeFun = (opt1) => {
            setTimeout(async () => {
                try {
                    console.log(`第${opt1.execFreq}次执行`);
                    let ret = await fn();
                    resolve(ret);
                } catch (e) {
                    if (opt1.execFreq === 0) {
                        // throw new Error(e);
                        reject(e);
                    } else {
                        console.log('setTimeOutExec.error:', e, opt1.timeOut, opt1.execFreq);
                        let execFreqTmp = opt1.execFreq - 1;
                        settimeFun({ timeOut: opt1.timeOut, execFreq: execFreqTmp });
                    }
                }
            }, opt1.timeOut);
        };
        settimeFun(opt);
    });
}

// 轮训执行函数 timeOut 函数执行间隔时间
export function setTimeOutExecFun(fn, checkFun, opt = { timeOut: 2000 }) {
    let execIndex = 0;
    return new Promise((resolve, reject) => {
        let settimeFun = (opt) => {
            setTimeout(async () => {
                let ret;
                try {
                    console.log(`循环调用次数：${execIndex}`);
                    ret = await fn();
                } catch (e) {
                    reject(e);
                }
                let checkRet = checkFun(ret);
                if (!checkRet) {
                    settimeFun(opt);
                } else {
                    resolve(checkRet);
                }
            }, opt.timeOut);
        };
        settimeFun(opt);
    });
}

export function generateGUID() {
    // 创建一个 16 字节的随机数组
    const array = new Uint8Array(16);
    window.crypto.getRandomValues(array);

    // 设置第6字节的高位为 4，符合 UUID v4 规范
    array[6] = (array[6] & 0x0f) | 0x40;

    // 设置第8字节的高位为 8、9、A 或 B，符合 UUID v4 规范
    array[8] = (array[8] & 0x3f) | 0x80;

    // 将字节数组转为字符串形式的 GUID
    let guid = '';
    for (let i = 0; i < 16; i++) {
        guid += (array[i] < 16 ? '0' : '') + array[i].toString(16);
        if (i === 3 || i === 5 || i === 7 || i === 9) guid += '-';
    }
    return guid;
}

// 全局遮罩实现嵌套方法
export async function appPageLoading(func) {
    window.pageLoading.openAll();
    try {
        await func();
    } catch (e) {
        throw new Error(e);
    } finally {
        window.pageLoading.closeAll();
    }
}

export function resetValues(orgData, defaultData) {
    Object.keys(orgData).forEach((key) => {
        orgData[key] = defaultData[key] || '';
    });
}
